<template>
  <div v-loading.lock="loading" class="base-content">
    <div class="basic-info storage-product-list">
      <el-form ref="queryForm" :inline="true" :model="queryForm" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="编号" prop="productNum">
              <el-input v-model="queryForm.productNum" placeholder="请输入编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryForm.name" placeholder="请输入名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="别名" prop="alias">
              <el-input v-model="queryForm.alias" placeholder="请输入别名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="CAS号" prop="casNum">
              <el-input v-model="queryForm.casNum" placeholder="请输入CAS号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类" prop="classOneId">
              <BaseTreeSelect
                v-model="queryForm.classOneId"
                :tree-data="categoryTree"
                placeholder="请选择分类"
                clearable
                @node-click="handleNodeClick"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
                <el-option label="全部" :value="null" />
                <el-option label="无效" :value="0" />
                <el-option label="有效" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="型号规格" prop="specifications">
              <el-input v-model="queryForm.specifications" placeholder="请输入型号规格" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间" prop="createDate">
              <el-date-picker
                v-model="queryForm.createDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="isException">
              <el-checkbox v-model="queryForm.isException">库存异常</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="onQuery">查询</el-button>
            <el-button @click="cancelForm">清空</el-button>
          </el-col>
        </el-row>
      </el-form>

      <div class="base-content-operate">
        <el-button
          v-rights="'Create'"
          icon="el-icon-plus"
          type="primary"
          @click="onNew"
          >新增</el-button
        >
        <el-button
          v-rights="'UpdateStatus'"
          type="primary"
          @click="updateStatus"
          >有效/无效</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-document-copy"
          @click="exportData"
          >导出</el-button
        >
      </div>

      <el-table
        :data="list"
        height="calc(100% - 130px)"
        style="width: 100%"
        :row-style="changeRowColor"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="编号">
          <template slot-scope="scope">
            <el-button
              v-rights="'Query'"
              size="mini"
              type="text"
              style="text-decoration:underline;"
              @click="handleView(scope.row)"
            >
              {{ scope.row.productNum }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="名称">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="别名">
          <template slot-scope="scope">
            {{ scope.row.alias }}
          </template>
        </el-table-column>
        <el-table-column label="型号规格">
          <template slot-scope="scope">
            {{ scope.row.specifications }}
          </template>
        </el-table-column>
        <el-table-column label="包装单位">
          <template slot-scope="scope">
            {{ scope.row.unitName }}
          </template>
        </el-table-column>
        <el-table-column label="CAS号">
          <template slot-scope="scope">
            {{ scope.row.casNum }}
          </template>
        </el-table-column>
        <el-table-column label="分类">
          <template slot-scope="scope">
            {{ scope.row.classOneName }}
          </template>
        </el-table-column>
        <el-table-column label="形态">
          <template slot-scope="scope">
            {{ scope.row.morphologyName }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            {{ scope.row.statusName }}
          </template>
        </el-table-column>
        <el-table-column label="实际库存">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.actualStore>0"
              size="mini"
              type="text"
              style="text-decoration:underline;"
              @click="handleLookStore(scope.row)"
            >
              {{ scope.row.actualStore }}
            </el-button>
            <el-button
              v-else
              size="mini"
              type="text"
            >
              {{ scope.row.actualStore }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="库存下限">
          <template slot-scope="scope">
            {{ scope.row.repertoryLower }}
          </template>
        </el-table-column>
        <el-table-column label="库存上限">
          <template slot-scope="scope">
            {{ scope.row.repertoryUpper }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="最近操作人">
          <template slot-scope="scope">
            {{ scope.row.updateUserName }}
          </template>
        </el-table-column>
        <el-table-column label="最近操作时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
          <div class="base-table-operation">
            <el-link v-rights="'Update'" size="mini" type="primary" @click="handleEdit(scope.row)"
              >编辑</el-link
            >
            <!-- <el-link
              v-rights="'Delete'"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-link
            > -->
          </div>
          </template>
        </el-table-column>
      </el-table>

      <BasePagination
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
    </div>

    <StorageProductEdit
      v-if="dialogFormVisible"
      ref="StorageProductEdit"
      :read-only.sync="readOnly"
      :edit-id.sync="editId"
      :dialog-form-visible.sync="dialogFormVisible"
    />
  </div>
</template>

<script>
import { deleteRecord, getList, getTreeData, updateStatus } from "../../../api/Storage/StorageProduct.js";
import StorageProductEdit from "./StorageProductEdit.vue";
import { formatData } from "../../../utils/index"

export default {
  name: "StorageProductList",
  components: { StorageProductEdit },
  data() {
    return {
      loading: true,
      list: [],
      categoryTree: [],
      appId: 1000,
      queryForm: {
        productNum: "",
        name: "",
        alias: "",
        casNum: "",
        classOneId: null,
        classTwoId: null,
        status: 1,
        specifications: "",
        createDate: [],
        isException: null
      },
      readOnly: false,
      selectionTables: [],
      dialogFormVisible: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      editId: ''
    };
  },
  created() {
    this.init();
    this.getList();
  },
  methods: {
    async init() {
      await this.getOptions();
    },
    changeRowColor({ row }) {
      console.log(row)
      if (row.isException === 1) { // 变颜色的条件
        return {
          backgroundColor: "#ED838F" // 这个return的就是样式 可以是color 也可以是backgroundColor
        }
      }
    },
    handleLookStore(rowData) {
      this.$router.push({
        path: "/Storage/StorageProductStoreList",
        query: {
          productNum: rowData.productNum
        },
      });
    },
    getOptions() {
      return new Promise((resolve) => {
        getTreeData({ AppId: this.appId, Status: 1 }).then((res) => {
          this.categoryTree = formatData(res.data);
          resolve();
        });
      })
    },
    handleNodeClick(data, node) {
      if (data.id !== null && data.id.length !== 0) {
        this.queryForm.classOneId = data.id;
      }
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    cancelForm() {
      this.$refs.queryForm.resetFields();
      this.pagination.pageIndex = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      const { createDate, ...queryForm } = this.queryForm
      getList({
        ...queryForm,
        isException: queryForm.isException ? 1 : 0,
        startCreateTime: Array.isArray(createDate) ? createDate[0] : '',
        endCreateTime: Array.isArray(createDate) ? createDate[1] : '',
        pageIndex: this.pagination.pageIndex,
        pageSize: this.pagination.pageSize
      })
        .then((res) => {
          this.list = res.data.dataList ? res.data.dataList : [];
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 新增
    onNew() {
      // this.$refs.StorageProductEdit.formData = this.Helper.deepCopy(
      //   this.$refs.StorageProductEdit.initData
      // );
      this.readOnly = false
      this.dialogFormVisible = true;
    },
    handleDelete(rowData) {
      this.Helper.deleteConfirm(() => {
        this.loading = true;
        deleteRecord({ id: rowData.id })
          .then((res) => {
            this.getList();
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    handleView(rowData) {
      this.readOnly = true
      this.dialogFormVisible = true;
      this.editId = rowData.id
    },
    handleEdit(rowData) {
      this.readOnly = false
      this.dialogFormVisible = true;
      this.editId = rowData.id
    },
    // 更新状态
    updateStatus() {
      if (this.selectionTables === null || this.selectionTables.length === 0) {
        this.$message.error("请选择数据");
        return false;
      }
      this.loading = true;
      updateStatus({ ids: this.selectionTables.map((v) => v.id) }).then((res) => {
        this.getList();
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    onQuery() {
      this.pagination.pageIndex = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      this.selectionTables = val
    },
    // 导出
    exportData() {
      var list = [];
      const { createDate, ...queryForm } = this.queryForm
      getList({
        ...queryForm,
        isException: queryForm.isException ? 1 : 0,
        startCreateTime: Array.isArray(createDate) ? createDate[0] : '',
        endCreateTime: Array.isArray(createDate) ? createDate[1] : '',
        pageIndex: 1,
        pageSize: 1000000
      }).then((res) => {
        list = res.data.dataList ? res.data.dataList : [];
        import("@/vendor/Export2Excel").then((excel) => {
          const tHeader = [
            "编号",
            "名称",
            "别名",
            "分类",
            "生产商",
            "生产商地址",
            "生产商电话",
            "CAS号",
            "形态",
            "型号规格",
            "包装单位",
            "净重（克）",
            "毛重（克）",
            "存储条件",
            "存储温度下限（℃）",
            "存储温度上限（℃）",
            "存储湿度下限（℃）",
            "存储湿度上限（℃）",
            "质保期",
            "质保期单位",
            "库存下限",
            "库存上限",
            "危险特性",
            "应急救援",
            "安全防护",
            "储运要求",
            "备注",
            "状态",
            "创建时间",
            "最近操作人",
            "最近操作时间"
          ];
          const filterVal = [
            "productNum",
            "name",
            "alias",
            "classOneName",
            "manufacturerName",
            "manufacturerAddress",
            "manufacturerMobile",
            "casNum",
            "morphologyName",
            "specifications",
            "unitName",
            "netWeight",
            "roughWeight",
            "storageConditionName",
            "temperatureLower",
            "temperatureUpper",
            "humidnessLower",
            "humidnessUpper",
            "warrantyPeriod",
            "warrantyPeriodUnit",
            "repertoryLower",
            "repertoryUpper",
            "hazardousCharacteristics",
            "emergencyRescue",
            "safetyProtection",
            "storeageConditions",
            "remark",
            "statusName",
            "createTime",
            "updateUserName",
            "updateTime"
          ];
          const data = this.formatJson(filterVal, list);
          excel.export_json_to_excel({
            header: tHeader, // 表头
            data, // 数据
            filename: "危化品产品信息", // 导出文件名
            autoWidth: true, // 导出宽度自动
            bookType: "xlsx", // 导出后缀
          });
        });
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
  },
};
</script>
<style lang="scss">
.storage-product-list{
  .el-form-item__content{
    width: calc(100% - 90px);
    .el-checkbox{
      margin-left: 50px;
    }
  }
}
</style>
